<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
 use Auth;
 use App\Models\ItemStock;
 use App\Models\PriceList;
 use App\Models\Customers;
 use App\Models\OrderMaster;
 use App\Models\OrderDetails;
class OrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function orderview()
    {
        $runners=[100222882,100222884,100222890,100222892,100222900,100222901,100222907,100222908,100222917,100214366,100222727,100222729,100222730,100218359,100214367,100222731,100222732,100222745,100219310,100214359,100214368,100222746,100222747,100216376,100216378,100216380,100216375,100216382,100216383,100216384,100214193,100214192,100214191
            ,100216366
            ,100216367
            ,100216368
            ,100216370
            ,100216371
            ,100216372
            ,100222899
            ,100222918
            ,100219309
            ,100214358
            ,100222744
            ,100216392
            ,100216374
            ,100216379
            ,100216389
            ,100222919
            ,100214357
            ,100222893
            ,100222909
            ,100222885
            ,100222916];

        $user=Auth::user();
        $created_by=$user->id;
        if($user->is_admin==1)
        { $branch_number=1;}
        else{
            $branch_number=2;
        }

        $all_item_stock=ItemStock::where('branch_number',$branch_number)->with('price')->get();

    //   dd($all_item_stock);

        // return view('create_order',compact('branch_number','all_item_stock','created_by'));
        return view('itemwithserial',compact('branch_number','all_item_stock','created_by'));

    }



    public function derCreate(Request $request)
    {
        // dd($request->Draft);

        if($request->Draft !=null)
        {
            $order_status=0;
        }
        else{
            $order_status=1;
        }
        $created_by=$request->created_by;
        $customer_name=$request->customer_name;
        // $customer_number=$request->customer_number;
        $customer_phone=$request->customer_phone;
        $customer_address=$request->customer_address;
        $customer_branch_number=$request->customer_branch_number;
        $customer_type=$request->customer_type;
        $discount=$request->discount;
        $Tax_amount=$request->Tax_amount;
        // $Net_amount=$request->Net_amount;
        // $quantityArr=$request->quantity;
        // $widthyArr=$request->width;
        $lengthArr=$request->length;

        $idStockItems=$request->iditem_stock;
        $payment_type=$request->payment_type;
        // $newQuantity=array_slice( $quantityArr, 0, count( $idStockItems));
        // $newWidth=array_slice( $widthyArr, 0, count( $idStockItems));
        $newLength=array_slice( $lengthArr, 0, count( $idStockItems));

        $order_type=$request->order_type;


        if($order_type==9) //بيع
        {
            $reforder=0;
        }
        else{
            $reforder=0; //temporary but i shoul get id og old order مرتجع
        }


        // create customer
        $newCustomer=new Customers;
        $newCustomer->customer_name=$customer_name;
        // $newCustomer->customer_number=$customer_number;
        $newCustomer->customer_number=$this->getLastCustomerNumberOfBranch($customer_branch_number)+1;
        $newCustomer->customer_phone=$customer_phone;
        $newCustomer->customer_address=$customer_address;
        $newCustomer->branch_number=$customer_branch_number;
        $newCustomer->customer_type=$customer_type;
        $newCustomer->save();
        if($newCustomer)
        {
                $message=$newCustomer;
        }
        else{
            $message='error in create customer';
        }
        $lastOrderNymber= $this->getLastOrderNumberOfBranch($customer_branch_number);
        // dd($lastOrderNymber);
        $newOrderNumber=$lastOrderNymber+1;

        //get selected item stock item
        $selected_item_stock=ItemStock::wherein('item_stock_id',$idStockItems)->with('price')->get();

        // create OrderMaster
        $newOrderMaster=new OrderMaster;
        $newOrderMaster->order_type=$order_type;
        $newOrderMaster->ref_order=$reforder;
        $newOrderMaster->branch_number=$customer_branch_number;
        $newOrderMaster->order_number=$newOrderNumber;
        $newOrderMaster->customer_number= $newCustomer->customer_number;
        $newOrderMaster->customer_name=$newCustomer->customer_name;
        $newOrderMaster->customer_phone=$newCustomer->customer_phone;
        $newOrderMaster->payment_type=$payment_type;
        $newOrderMaster->created_by=$created_by;
        $newOrderMaster->discount=$discount;
        $newOrderMaster->tax_amount=$Tax_amount;
        $newOrderMaster->order_status=$order_status;
        // $newOrderMaster->net_amount=$Net_amount;
        $newOrderMaster->total_amount=0; //untill get all total amount from insert order details
        // dd($lastOrderNymber);
        $newOrderMaster->save();
        if($newOrderMaster)
        {
            $allDetails=[];
            $Iterator=0;
            $totalAmount=0;
            foreach ($selected_item_stock as $item) {
                // dd($newLength[$Iterator]);
                $newWidth=$item->item_width;
                $newLength1=$newLength[$Iterator];
                $itemQuantity=($newWidth * $newLength1)/10000;
                $itemTotalPrice=($item->price->item_price *  $itemQuantity);
                $newOrderDetails=new OrderDetails;
                $newOrderDetails->order_number=$newOrderMaster->order_number;
                // $newOrderDetails->branch_number=$customer_branch_number;
                $newOrderDetails->branch_number=$customer_branch_number;
                $newOrderDetails->item_code=$item->item_code;
                $newOrderDetails->ref_code=$item->ref_code;
                $newOrderDetails->item_serial=$item->item_serial;
                $newOrderDetails->item_price=$item->price->item_price;
                $newOrderDetails->item_width=$newWidth;
                $newOrderDetails->item_length=$newLength1;
                $newOrderDetails->item_class=$item->item_class;

                $newOrderDetails->item_quantity=$itemQuantity;

                $newOrderDetails->total_price=$itemTotalPrice;
                $totalAmount +=$itemTotalPrice;
                $Iterator +=1;
                // dd(count($selected_item_stock));
                $newOrderDetails->save();
                array_push($allDetails, $newOrderDetails);

                if($order_status==1)//cut from length and quantity of item stock
                {
                    $itemStocklengthAfterOrder=($item->item_length -$newLength1);
                    $itemStockQuantityAfterOrder=($itemStocklengthAfterOrder * $item->item_width)/10000;
                    $newItemStockUpdate=ItemStock::where('item_stock_id', $item->item_stock_id)

                    ->update(['item_quantity' => $itemStockQuantityAfterOrder,'item_length'=>$itemStocklengthAfterOrder]);

                }

            }
            // $newOrderMaster->total_amount=$totalAmount;
            // $newOrderMaster->save();

      $netstate =$totalAmount;
       if($discount !=0)
       {
        $netstate=$totalAmount-$discount;
       }
       if($Tax_amount !=0)
       {
        $netstate=$totalAmount+$Tax_amount;
       }
    //    dd($newOrderMaster->id);
            $newOrderMasterUpdate=OrderMaster::where('order_master_id', $newOrderMaster->id)

            ->update(['total_amount' => $totalAmount,'net_amount'=>$netstate]);

        }
        $lastorderMasterAfterUpdate=OrderMaster::where('order_master_id', $newOrderMaster->id)->first();
        if($order_status ==1)
        {
            return view('invoice',compact('lastorderMasterAfterUpdate','allDetails','created_by'));
        }


// dd($newOrderMasterUpdate);






        //
    }


    public function getLastOrderNumberOfBranch($branch_number)
    {

        $orderNumber = \DB::table('order_master')->where('branch_number',$branch_number)->latest('order_number')->first();
        if($orderNumber==null)
        {
            return 0;
        }
        return  $orderNumber->order_number;
    //    return $orderNumber= OrderMaster::select('order_number')->where('branch_number',$branch_number)->getPdo()->lastInsertId();

    }


    public function getLastCustomerNumberOfBranch($branch_number)
    {

        $customerNumber = \DB::table('customers')->where('branch_number',$branch_number)->latest('customer_number')->first();
        if($customerNumber==null)
        {
            return 0;
        }
        return  $customerNumber->customer_number;
    //    return $orderNumber= OrderMaster::select('order_number')->where('branch_number',$branch_number)->getPdo()->lastInsertId();

    }

    public function retrivedorderview()
    {
        $user=Auth::user();
        $created_by=$user->id;
        if($user->is_admin==1)
        { $branch_number=1;}
        else{
            $branch_number=2;
        }

        $allConfirmedOrders2=OrderMaster::select('order_number')->where('ref_order',0)->where('order_status', 1)->where('branch_number', $branch_number)->where('order_type',9)->get();
        $allConfirmedOrders =[];
        foreach($allConfirmedOrders2 as $key => $allConfirmedOrderss){
            //return $allConfirmedOrderss['order_number'];
            $findreforderintable = OrderMaster::where('ref_order',$allConfirmedOrderss['order_number'])->get();
            if(count($findreforderintable) > 0){

            }else{
                $findreforderintable2 = OrderMaster::where('order_number',$allConfirmedOrderss['order_number'])->with('details')->get();
                array_push($allConfirmedOrders,$findreforderintable2[0]);
            }

        }
       $allConfirmedOrders;
    //     $order_numbers=[];
    //     foreach($allConfirmedOrders as $order)
    //   {
    //     array_push($order_numbers,$order->order_number);
    //   }
    //   $allConfirmedOrdersnotretrivedBefor=OrderMaster::where('order_status', 1)->where('branch_number', $branch_number)->where('order_type',9)->whereNotIn('ref_order',$order_numbers)->with('details')->get();


        //dd( $allConfirmedOrdersnotretrivedBefor);
        return view('retrive_order2',compact('allConfirmedOrders'));
    }


    public function  retrivedorder($order_number,Request $request)
    {
        $branch_number=$request->branch_number;
        $retrivedOrder=OrderMaster::where(['order_number'=> $order_number,'branch_number'=> $branch_number,'order_status'=>1])->with('details')->first();
    //   dd($retrivedOrder);
        $user=Auth::user();
        $created_by=$user->id;

if($request->partial !=null)
{

    $IDofSelectedItems=$request->iditem_details;
    $selectedItemsToRetrive=OrderDetails::wherein('order_details_id',$IDofSelectedItems)->get();
    // dd($selectedItemsToRetrive);
    $newordernumber=$this->getLastOrderNumberOfBranch($branch_number)+1;
    $order_type=10; //جزئي مرتجع

    $newOrderMaster=new OrderMaster;
    $newOrderMaster->order_type=$order_type;
    $newOrderMaster->ref_order=$retrivedOrder->order_number;
    $newOrderMaster->branch_number=$branch_number;
    $newOrderMaster->order_number=$newordernumber;
    $newOrderMaster->customer_number= $retrivedOrder->customer_number;
    $newOrderMaster->customer_name=$retrivedOrder->customer_name;
    $newOrderMaster->customer_phone=$retrivedOrder->customer_phone;
    $newOrderMaster->payment_type=$retrivedOrder->payment_type;
    $newOrderMaster->created_by=$created_by;
    $newOrderMaster->discount=0;
    $newOrderMaster->tax_amount=0;
    $newOrderMaster->order_status=1;
    $newOrderMaster->net_amount=$retrivedOrder->net_amount;
    $newOrderMaster->total_amount=$retrivedOrder->total_amount; //untill get all total amount from insert order details
    // dd($lastOrderNymber);
    $newOrderMaster->save();

    if($newOrderMaster)
    {
        $allDetails=[];
        $Iterator=0;
        $totalAmount=0;
        foreach ($selectedItemsToRetrive as $item) {
            // dd($newLength[$Iterator]);
            $newWidth=$item->item_width;
            $newLength=$item->item_length;
            $itemQuantity=$item->item_quantity;
            $itemTotalPrice=$item->total_price;
            $newOrderDetails=new OrderDetails;
            $newOrderDetails->order_number=$newOrderMaster->order_number;
            // $newOrderDetails->branch_number=$customer_branch_number;
            $newOrderDetails->branch_number=$branch_number;
            $newOrderDetails->item_code=$item->item_code;
            $newOrderDetails->ref_code=$item->ref_code;
            $newOrderDetails->item_serial=$item->item_serial;
            $newOrderDetails->item_price=$item->item_price;
            $newOrderDetails->item_width=$newWidth;
            $newOrderDetails->item_length=$newLength;
            $newOrderDetails->item_class=$item->item_class;

            $newOrderDetails->item_quantity=$itemQuantity;

            $newOrderDetails->total_price=$itemTotalPrice;

            // dd(count($selected_item_stock));
            $newOrderDetails->save();

            $itemStocktoupdate=ItemStock::where('item_serial', $item->item_serial)->where('branch_number',$branch_number)->first();
            // array_push($allDetails, $newOrderDetails);

           //cut from length and quantity of item stock

                $itemStocklengthAfterOrder=($itemStocktoupdate->item_length +$newLength);
                $itemStockQuantityAfterOrder=($itemStocklengthAfterOrder * $itemStocktoupdate->item_width)/10000;
                $newItemStockUpdate=ItemStock::where('item_stock_id', $itemStocktoupdate->item_stock_id)

                ->update(['item_quantity' => $itemStockQuantityAfterOrder,'item_length'=>$itemStocklengthAfterOrder]);



        }
    }


}






if($request->Confirm !=null)
        {
            $newordernumber=$this->getLastOrderNumberOfBranch($branch_number)+1;
            $order_type=10; //كلي مرتجع

            $newOrderMaster=new OrderMaster;
            $newOrderMaster->order_type=$order_type;
            $newOrderMaster->ref_order=$retrivedOrder->order_number;
            $newOrderMaster->branch_number=$branch_number;
            $newOrderMaster->order_number=$newordernumber;
            $newOrderMaster->customer_number= $retrivedOrder->customer_number;
            $newOrderMaster->customer_name=$retrivedOrder->customer_name;
            $newOrderMaster->customer_phone=$retrivedOrder->customer_phone;
            $newOrderMaster->payment_type=$retrivedOrder->payment_type;
            $newOrderMaster->created_by=$created_by;
            $newOrderMaster->discount=0;
            $newOrderMaster->tax_amount=0;
            $newOrderMaster->order_status=1;
            $newOrderMaster->net_amount=$retrivedOrder->net_amount;
            $newOrderMaster->total_amount=$retrivedOrder->total_amount; //untill get all total amount from insert order details
            // dd($lastOrderNymber);
            $newOrderMaster->save();
            if($newOrderMaster)
            {
                $allDetails=[];
                $Iterator=0;
                $totalAmount=0;
                foreach ($retrivedOrder->details as $item) {
                    // dd($newLength[$Iterator]);
                    $newWidth=$item->item_width;
                    $newLength=$item->item_length;
                    $itemQuantity=$item->item_quantity;
                    $itemTotalPrice=$item->total_price;
                    $newOrderDetails=new OrderDetails;
                    $newOrderDetails->order_number=$newOrderMaster->order_number;
                    // $newOrderDetails->branch_number=$customer_branch_number;
                    $newOrderDetails->branch_number=$branch_number;
                    $newOrderDetails->item_code=$item->item_code;
                    $newOrderDetails->ref_code=$item->ref_code;
                    $newOrderDetails->item_serial=$item->item_serial;
                    $newOrderDetails->item_price=$item->item_price;
                    $newOrderDetails->item_width=$newWidth;
                    $newOrderDetails->item_length=$newLength;
                    $newOrderDetails->item_class=$item->item_class;

                    $newOrderDetails->item_quantity=$itemQuantity;

                    $newOrderDetails->total_price=$itemTotalPrice;

                    // dd(count($selected_item_stock));
                    $newOrderDetails->save();

                    $itemStocktoupdate=ItemStock::where('item_serial', $item->item_serial)->where('branch_number',$branch_number)->first();
                    // array_push($allDetails, $newOrderDetails);

                   //cut from length and quantity of item stock

                        $itemStocklengthAfterOrder=($itemStocktoupdate->item_length +$newLength);
                        $itemStockQuantityAfterOrder=($itemStocklengthAfterOrder * $itemStocktoupdate->item_width)/10000;
                        $newItemStockUpdate=ItemStock::where('item_stock_id', $itemStocktoupdate->item_stock_id)

                        ->update(['item_quantity' => $itemStockQuantityAfterOrder,'item_length'=>$itemStocklengthAfterOrder]);



                }
            }
        }
    }


    public function getItemStockBySerial(Request $request)
    {
    //    return($request->serial);
        $item = ItemStock::where('item_serial',$request->serial)->get();
        if (count($item) > 0){
            return $item[0];
        }else{
            return $item = ["item_serial"=>"not found"];
        }
    }
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
