<?php
namespace App\Http\Controllers;

use App\Http\Requests\OrderStoreRequest;
use App\Models\Order;
use App\Models\Customer;
use App\Models\OrderItem;
use App\Models\Payment;
use App\Models\User_Cart;
use App\Models\Product;
use Illuminate\Http\Request;
use App\transactions;
use App\banks;
use App\expenses;
use App\shifts;

class OrderController extends Controller
{


public function showShiftReport($shiftId)
{
    // Get the shift
    $shift = shifts::findOrFail($shiftId);

    // Get all orders related to the shift (shift_id = $shiftId in the order table)
    $orders = Order::where('shift_id', $shiftId)->orderby('id','desc')->get();

    // Initialize an array to store item details and revenue
    $items = [];
    $totalRevenue = 0;

    // Loop through each order and get the order items
    foreach ($orders as $order) {
        $orderItems = OrderItem::where('order_id', $order->id)->get();

        foreach ($orderItems as $item) {
            $product = Product::find($item->product_id); // Assuming you have a Product model
            $itemRevenue = $item->price * $item->quantity;

            // Store item data for report
            if (!isset($items[$product->name])) {
                $items[$product->name] = [
                    'quantity' => 0,
                    'revenue' => 0
                ];
            }

            $items[$product->name]['quantity'] += $item->quantity;
            $items[$product->name]['revenue'] += $itemRevenue;

            // Add to the total revenue
            $totalRevenue += $itemRevenue;
        }
    }

    // Get expenses related to the shift (assuming expenses have a shift_id column)
    $expenses = expenses::where('shift_id', $shiftId)->get(); // Assuming expenses are linked to shifts

    // Calculate the total expense
    $totalExpense = $expenses->sum('expense_price');

    // Pass the shift, orders, items, totalRevenue, and expenses to the view
    return view('shifts.shift_report', compact('shift', 'orders', 'items', 'totalRevenue', 'expenses', 'totalExpense'));
}




public function begin_shift() {
    // Get the last shift
    $last_shift = shifts::orderBy('id', 'desc')->first();

    // If there is no last shift, this is the first shift
    if (!$last_shift) {
        // Create the first shift (no last shift to check)
        $shift = new shifts();
        $shift->shift_begin = now();
        $shift->user_id = auth()->user()->id; // Assuming the user is authenticated
        $shift->save(); // Save the new shift record

        return redirect()->back()->with('message', 'الوردية الأولى بدأت بنجاح');
    }

    // Check if the last shift has ended
    if ($last_shift->shift_end == null) {
        // If the last shift hasn't ended, we can't start a new one
        return redirect()->back()->with('error', 'الوردية الأخيرة لم تُغلق بعد. لا يمكن بدء وردية جديدة.');
    }

    // If the last shift has ended, start a new shift
    $shift = new shifts();
    $shift->shift_begin = now();
    $shift->user_id = auth()->user()->id; // Assuming the user is authenticated
    $shift->save(); // Save the new shift record

    return redirect()->back()->with('message', 'الوردية بدأت بنجاح');
}








public function close_shift() {
    // Retrieve the last shift (find the open shift)
    $last_shift = shifts::whereNull('shift_end')->orderBy('id', 'desc')->first();

    // If there is no open shift, return an error (can't close a shift that isn't open)
    if (!$last_shift) {
        return redirect()->back()->with('error', 'لا يوجد وردية مفتوحة حاليا');
    }

    // Retrieve first and last order (if needed for calculations)
    $first_order = Order::where('shift_id', '0')->orderBy('id', 'asc')->first();
    $last_order = Order::where('shift_id', '0')->orderBy('id', 'desc')->first();

    // Use the first order's created_at as the shift begin time if needed
    $shift_begin = $last_shift->shift_begin;

    // Set the shift end time as now
    $shift_end = now();

    // Retrieve orders in this shift (with shift_id = 0)
    $shift_orders = Order::where('shift_id', '0')->get();
    $shift_orders_total = $shift_orders->count(); // Number of orders

    // Retrieve expenses during this shift period
    $shift_expenses = expenses::whereBetween('created_at', [$shift_begin, $shift_end])->get();

    // Calculate total income (sum of cash payments for orders)
    $shift_total_income = 0;
    foreach ($shift_orders as $shift_order) {
        $payments_in_shift = Payment::where('order_id', $shift_order->id)->first();
        if ($payments_in_shift) {
            $shift_total_income += $payments_in_shift->cash; // Add cash payments
        }
    }

    // Calculate total expenses
    $shift_total_expenses = $shift_expenses->sum('expense_price'); // Sum of all expenses

    // Calculate net profit
    $shift_net_profit = $shift_total_income - $shift_total_expenses;

    // Update the existing shift record
    $last_shift->shift_end = $shift_end;
    $last_shift->total_expenses = $shift_total_expenses;
    $last_shift->total_sales = $shift_orders_total;
    $last_shift->total_revenue = $shift_total_income; // Total income as revenue
    $last_shift->net_profit = $shift_net_profit;
    $last_shift->user_id = auth()->user()->id; // Authenticated user closing the shift
    $last_shift->save(); // Save the updated shift record

    // Updating orders with shift_id
    foreach ($shift_orders as $shift_order) {
        $shift_order->shift_id = $last_shift->id; // Assign the shift_id to the orders
        $shift_order->update();
    }

    // Updating expenses with shift_id
    foreach ($shift_expenses as $expense) {
        $expense->shift_id = $last_shift->id; // Assign the shift_id to the expenses
        $expense->update();
    }

    return redirect()->back()->with('message', 'الوردية تم إغلاقها بنجاح');
}



/*
	public function close_shift() {
		
		$first_order = Order::where('shift_id','0')->orderby('id','asc')->first();
		$last_order = Order::where('shift_id','0')->orderby('id','desc')->first();


		//******* start check shift exist *******
		$last_shift = shifts::orderby('id','desc')->first();
		
		if($last_shift->shift_end == null) 
		//**** last shift exist and begun but not closed yet
		{
			
				$shift_begin = $last_shift->shift_begin;
		}
		else {
		//**** shift begun without clicking start shift
			
			// make the begining time from the first order
			$shift_begin = $first_order->created_at;

		}

		$shift_end = NOW();
		//******* end check shift exist *******




		$shift_orders = Order::where('shift_id','0')->get();
		$shift_expenses = expenses::whereBetween('created_at', [$shift_begin, $shift_end])->get();

		
		$shift_total_income = 0;
		
		foreach($shift_orders as $shift_order) {
			$payments_in_shift = Payment::where('order_id',$shift_order->id)->first();
			$cash = $payments_in_shift->cash;
			$shift_total_income = $shift_total_income + $cash;
		}
		
	}
*/

    public function search_by_client($client_name) {

        $customers = Customer::where('first_name', 'LIKE', $client_name)
        ->orWhere('last_name','LIKE',$client_name)
        ->get('id');

        //dd($customers);

        $orders = new Order;

        foreach($customers as $r) {
            $orders = $orders->orwhere('customer_id',$r->id);
        }

        $orders = $orders->where('order_status','active')
        ->where('type','sale')->Orderby('id','desc');

       $orders = $orders->where('status','done');


        $orders = $orders->paginate('150');

        return view('/orders/search_results',compact('orders'));
        
    }



    public function destroy($order_id) {

        $order = Order::find($order_id);
        $order->delete();
        return redirect('/admin/orders');
        
    }



   public function invoice_edit ($invoice_id) {

        $orders = Order::where('id',$invoice_id)->get();
        $order_info = Order::where('id',$invoice_id)->first();


            $cart = User_Cart::where('id','>','0');
            $cart->delete();

            //dd('hii');

            $order_items = OrderItem::where('order_id',$invoice_id)
            ->where('item_status','active')
            ->get();


            foreach($order_items as $item) {

                $user_cart = new User_Cart;
                $user_cart->user_id = auth()->user()->id;
                $user_cart->product_id = $item->product_id;
                $user_cart->quantity = $item->quantity;
                $user_cart->unit_id = $item->unit_id;
                $user_cart->save();

            }

            $this->refund($order_info->id);


            return redirect('admin/pos'.'/'.$invoice_id.'/'.$order_info->customer_id);




    }



   public function refund ($invoice_id) {




        $orders = Order::where('id',$invoice_id)->get();

       // $order_info = Order::where('id',$invoice_id)->first();

       // $customer = Customer::where('id',$order_info->user_id)->first();
       // $customer->paid = 0;
      //  $customer->update();

       // $order_info->user_id;

        
        foreach ($orders as $r_orders) {


            $r_orders->order_status = "refunds";
            $r_orders->update();

            $order_items = OrderItem::where('order_id',$r_orders->id)
            ->where('item_status','active')
            ->get();


            foreach($order_items as $items) {
            
            $store = \App\Models\Product::where('id',$items->product_id)->first();
            $store->quantity = $store->quantity + $items->quantity;
            $store->update();

            $items->item_status = "refund";
            $items->update();
            }





            $payments = Payment::where('order_id',$r_orders->id)->get();

            foreach($payments as $items) {
            $items->order_status = "refund";
            $items->update();
            }


        }



        $payment2 = Payment::where('order_id',$invoice_id)->first();



        $type = 'depit';
        $trans = new transactions;
        $trans->type = 'depit';
        $trans->amount = $payment2->bankak + $payment2->cash + $payment2->shake;
        $trans->payment_method = 'cash';
        $trans->notes = 

        "مبيعات - الغاء فاتورة     ";
        $trans->trans_type = "sale";
        $trans->trans_type_id = $invoice_id;
        $trans->save();

        $banks = banks::where('id','1')->first();

        if($type == "credit") {
        $banks->balance = $banks->balance +  $payment2->bankak + $payment2->cash + $payment2->shake;
        }
        if($type == "depit") {
        $banks->balance = $banks->balance -   $payment2->bankak + $payment2->cash + $payment2->shake;
        }

        $banks->update();




        
        return redirect('admin/orders');
    }




   public function expire_checked ($id) {





        $orders = OrderItem::where('id',$id)->get();

        // $orders->status = "done";
        // $orders->update();

        
        foreach ($orders as $r_orders) {


            $r_orders->expire_status = "checked";
            $r_orders->update();

        }


        return redirect('products/expired');
    }




   public function done_pay_customer ($customer_id) {





        $orders = Order::where('customer_id',$customer_id)->get();

        // $orders->status = "done";
        // $orders->update();


        
        foreach ($orders as $r_orders) {

            $payments = \App\Models\Payment::where('order_id',$r_orders->id)->first();

            $remaining = 0;

            $remaining = $payments->amount - $payments->discount - $payments->bankak + $payments->cash + $payments->shake;

            $payments->cash = $remaining;

            $payments->update();

            
            $r_orders->status = "done";
            $r_orders->update();

            $order_items = OrderItem::where('order_id',$r_orders->id)->get();


            foreach($order_items as $items) {
            $items->status = "done";
            $items->update();
            }



        }


        $customer = Customer::where('id',$customer_id)->first();

        $customer->status = "done";
        $customer->paid = 0;
        $customer->update();


        $customer_payments = \App\customers_payments::where('customer_id',$customer_id)->get();

        foreach($customer_payments as $customer_payments)
        {
            $customer_payments->status = "done";
            $customer_payments->update();
        }

        
        return redirect('admin/orders_by_customers');
    }




    public function report_on_user() { 
        $user_id = request()->input('user_id');

       $from = request()->input('date_from');
        $to = request()->input('date_to');


   // $orders = new Order();
        //if($request->start_date) {
  //        
   //     $orders = Order::where('user_id',$user_id)
   //    ->whereBetween('created_at', [$from." 00:00:00", $to." 23:59:59"]);
   //    
  //     $orders = $orders->where('order_status','active')
   //   ->where('type','sale')
  //     ->where('status','done');

$orders = Order::where('user_id', $user_id)
               ->whereBetween('created_at', [$from." 00:00:00", $to." 23:59:59"])
               ->where('order_status', 'active')
               ->where('type', 'sale')
               ->where('status', 'done');


 
        $orders2 = $orders->with(['items', 'payments', 'customer'])->latest()->get();
        $orders = $orders->with(['items', 'payments', 'customer'])->latest()->paginate(100);


        $all_total = $orders2->map(function($i) {
            return $i->total();
        })->sum();

        $discount = $orders2->map(function($i) {
            return $i->discountAmount();
        })->sum();


        $total = $orders->map(function($i) {
            return $i->total();
        })->sum();
        $receivedAmount = $orders->map(function($i) {
            return $i->receivedAmount();
        })->sum();

        return view('orders.index', compact('orders', 'total','all_total','discount', 'receivedAmount','user_id'));





    /*    $orders = Order::where('user_id',$user_id)
        ->whereBetween('created_at', [$from, $to])
        ->get();

        $total = 0;
 
        foreach($orders as $r)
        {
           $total = $total + $r->price;
        }



        return view('orders.index',compact('orders'));
*/

    }
 



    public function index_purchase(Request $request) {
        $orders = new Order();

       $orders = $orders->where('status','done');
       $orders = $orders->where('type','purchase');

        if($request->start_date) {
            $orders = $orders->where('created_at', '>=', $request->start_date);
        }
        if($request->end_date) {
            $orders = $orders->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }



        $orders2 = $orders->with(['items', 'payments', 'customer'])->latest()->get();
        $orders = $orders->with(['items', 'payments', 'customer'])->latest()->paginate(10);


        $all_total = $orders2->map(function($i) {
            return $i->total_purchases();
        })->sum();


        $discount = $orders2->map(function($i) {
            return $i->discountAmount();
        })->sum();


        $total = $orders->map(function($i) {
            return $i->total_purchases();
        })->sum();

        $receivedAmount = $orders->map(function($i) {
            return $i->receivedAmount();
        })->sum();


        return view('orders.index_purchase', compact('orders', 'total','all_total','discount', 'receivedAmount'));
    }




    public function index(Request $request) {
        $orders = new Order();

       $orders = $orders->OrderBy('id','desc');
     //  $orders = $orders->where('status','done');
       $orders = $orders->where('type','sale');
       $orders = $orders->where('order_status','active');




/////////////////////////////////begin from the index//////////////////







////////////////////////////// end from begin //////////////////////









        if($request->start_date) {
            $orders = $orders->where('created_at', '>=', $request->start_date);
        }
        if($request->end_date) {
            $orders = $orders->where('created_at', '<=', $request->end_date . ' 23:59:59');
        }

		$orders = $orders->where('shift_id','0');


        $orders2 = $orders->with(['items', 'payments', 'customer'])->latest()->get();
        $orders = $orders->with(['items', 'payments', 'customer'])->latest()->paginate(50);


        $all_total = $orders2->map(function($i) {
            return $i->receivedAmount();
        })->sum();


        $discount = $orders2->map(function($i) {
            return $i->discountAmount();
        })->sum();


        $total = $orders->map(function($i) {
            return $i->total();
        })->sum();

        $receivedAmount = $orders->map(function($i) {
            return $i->receivedAmount();
        })->sum();


        return view('orders.index', compact('orders', 'total','all_total','discount', 'receivedAmount'));
    }


 public function store2($customer_id,$amount,$discount,$net_profit,$bankak,$cash,$shake,$special,$invoice_id)
    {

		$fiirst_order_in_shift = \App\Models\Order::where('shift_id','0')->count();
		if($fiirst_order_in_shift == 0)
		{
			$v_id = 1;
		}
		else {
			$v_id = \App\Models\Order::orderby('id','desc')->first()->v_id;
			$v_id = $v_id + 1;
		}
		
        if($invoice_id > 0){
            $the_invoice = $invoice_id;

            $order = Order::where('id',$invoice_id);
            $order_items = OrderItem::where('order_id',$invoice_id);
            $order_payments = Payment::where('order_id',$invoice_id);

            $order->delete();
            $order_items->delete();
            $order_payments->delete();


        }
        else {
            $the_invoice = null;
        }
       



    if($amount - $discount <= $bankak+$cash+$shake) {

        $order = Order::create([
            'id' => $the_invoice,
            'v_id' => $v_id,
            'customer_id' => $customer_id,
            'user_id' => auth()->user()->id,
            'discount' => $discount,
            'net_profit' => $net_profit,
            'status' => 'done',
            'special' => $special,
        ]);


    }
    else {

        $order = Order::create([
            'id' => $the_invoice,
            'v_id' => $v_id,
            'customer_id' => $customer_id,
            'user_id' => auth()->user()->id,
            'discount' => $discount,
            'net_profit' => $net_profit,
            'special' => $special,
        ]);

        $customer = Customer::find($customer_id);
        $customer->paid = $customer->paid + $bankak + $cash + $shake;
        $customer->update();

        $customer_payments = new \App\customers_payments;
        $customer_payments->customer_id = $customer_id;

        $method = "";

        if($cash > 0) {
        $method = $method . " cash ";
        }

        if($bankak > 0) {
        $method = $method . " bankak ";
        }
        if($shake > 0) {
        $method = $method . " shake ";
        }

        $customer_payments->payment_method = $method;
        $customer_payments->amount = $bankak + $cash + $shake;
        $customer_payments->notes = " المدفوع   بنكك :  ".
        $bankak." المدفوع كاش :  ".$cash." المدفوع    شيك  :  ".$shake."د فعية مع الفاتورة  رقم  " . $order->id;
        $customer_payments->status = "not_done";
        $customer_payments->save();

    }
   


        $cart = auth()->user()->cart()->get();



        //$item contain product info 
        //$item->pivot contain cart info 


        foreach ($cart as $item) {

            if($item->pivot->unit_id > 0) {

            $unit = \App\units::where('id',$item->pivot->unit_id)->first();


            $order->items()->create([
                'unit_id' => $item->pivot->unit_id,
                'price' => $unit->price,
                'quantity' => $item->pivot->quantity,
                'product_id' => $item->id,
            ]);


            $item->quantity = $item->quantity - ($item->pivot->quantity / $unit->quantity);
            $item->save();

            } else { 



            $unit = \App\units::where('id',$item->pivot->unit_id)->first();

            $order->items()->create([
                'unit_id' => $item->pivot->unit_id,
                'price' => $item->price,
                'quantity' => $item->pivot->quantity,
                'product_id' => $item->id,
            ]);
            $item->quantity = $item->quantity - ($item->pivot->quantity / $unit->quantity);
            $item->save();


            }



        }



        auth()->user()->cart()->detach();
        $order->payments()->create([
            'amount' => $amount,
            'discount' => $discount,
            'net_profit' => $net_profit,
            'bankak' => $bankak,
            'cash' => $cash,
            'shake' => $shake,
            'user_id' => auth()->user()->id,
        ]);
        

        $method = "";
        if($bankak > 0) {
            $method = $method . ' bankak ';
        }

        if($cash > 0) {
            $method = $method . ' cash ';
        }

        if($shake > 0) {
            $method = $method . ' shake ';
        }


        $customer = \App\Models\Customer::find($customer_id)->first();

        $type = 'credit';
        $trans = new transactions;
        $trans->type = 'credit';
        $trans->amount = $bankak + $cash + $shake;
        $trans->payment_method = $method;
        $trans->notes = 
       /* " فاتورة رقم  ".$order->id."-".
        " اجمالي الفاتورة  ".$amount."-".
        "  قيمة الخصم   ".$discount."-".
        " العميل  : " . 
       $customer->first_name." ".$customer->last_name
        ."<br>".
        " تاريخ الفاتورة   ".$order->created_at."-".
        " الموظف   ". auth()->user()->first_name ." ".auth()->user()->last_name."-".
        */

        "مبيعات   - المدفوع بنكك  " .  $bankak . " المدفوع  كاش   " .  $cash . " المدفوع  شيك  " .  $shake  ;
        $trans->trans_type = "sale";
        $trans->trans_type_id = $order->id;
        $trans->save();

        $banks = banks::where('id','1')->first();

        if($type == "credit") {
        $banks->balance = $banks->balance + $cash + $bankak + $shake;
        }
        if($type == "depit") {
        $banks->balance = $banks->balance -  $cash + $bankak + $shake;
        }

        $banks->update();









        

    }







 public function store2_purchase($customer_id,$amount,$discount,$net_profit,$bankak,$cash,$shake)
    {
       



    if($customer_id == 4) {

        $order = Order::create([
            'customer_id' => $customer_id,
            'user_id' => auth()->user()->id,
            'discount' => $discount,
            'net_profit' => $net_profit,
            'status' => 'done',
            'type' => 'purchase',
        ]);


    }
    else {

        $order = Order::create([
            'customer_id' => $customer_id,
            'user_id' => auth()->user()->id,
            'discount' => $discount,
            'net_profit' => $net_profit,
            'status' => 'not_done',
            'type' => 'purchase',
        ]);

        $customer = Customer::find($customer_id);
        $customer->paid = $customer->paid + $bankak + $cash + $shake;
        $customer->update();

    }
   


        $cart = auth()->user()->cart_purchase()->get();
        foreach ($cart as $item) {
            $order->items()->create([
                'price' => $item->buy_price,
                'expire_date' => $item->pivot->expire_date,
                'quantity' => $item->pivot->quantity,
                'product_id' => $item->id,
                'type' => 'purchase',
            ]);
            $item->quantity = $item->quantity + $item->pivot->quantity;
            $item->save();

        }



        auth()->user()->cart_purchase()->detach();
        $order->payments()->create([
            'amount' => $amount,
            'discount' => $discount,
            'net_profit' => $net_profit,
            'bankak' => $bankak,
            'type' => 'purchase',
            'cash' => $cash,
            'shake' => $shake,
            'user_id' => auth()->user()->id,
        ]);
        




        $method = "";
        if($bankak > 0) {
            $method = $method . ' bankak ';
        }

        if($cash > 0) {
            $method = $method . ' cash ';
        }

        if($shake > 0) {
            $method = $method . ' shake ';
        }


        $customer = \App\Models\Customer::find($customer_id)->first();

        $type = 'depit';
        $trans = new transactions;
        $trans->type = 'depit';
        $trans->amount = $bankak + $cash + $shake;
        $trans->payment_method = $method;
        $trans->notes = 

        "مشتريات    - المدفوع بنكك  " .  $bankak . " المدفوع  كاش   " .  $cash . " المدفوع  شيك  " .  $shake  ;
        $trans->trans_type = "purchase";
        $trans->trans_type_id = $order->id;
        $trans->save();

        $banks = banks::where('id','1')->first();

        if($type == "credit") {
        $banks->balance = $banks->balance + $cash + $bankak + $shake;
        }
        if($type == "depit") {
        $banks->balance = $banks->balance -  $cash + $bankak + $shake;
        }

        $banks->update();












        

    }





    public function store(OrderStoreRequest $request)
    {
        $order = Order::create([
            'customer_id' => $request->customer_id,
            'user_id' => $request->user()->id,
        ]);

        $cart = $request->user()->cart()->get();
        foreach ($cart as $item) {
            $order->items()->create([
                'price' => $item->price,
                'quantity' => $item->pivot->quantity,
                'product_id' => $item->id,
            ]);
            $item->quantity = $item->quantity - $item->pivot->quantity;
            $item->save();
        }
        $request->user()->cart()->detach();
        $order->payments()->create([
            'amount' => $request->amount,
            'user_id' => $request->user()->id,
        ]);
        return 'success';
    }










/*



            $product = \App\Models\Product::where('id',$item->id)->first();
           
           
            if($product->quantity == 0 && $product->father_id > 0) {
                
            //get father product to minus it by 1 
            $product2 = \App\Models\Product::where('id',$product->id)->first();
            $product2->quantity = $product2->quantity - 1;
            $product2->save();


            // put the full quantity inside the one was 0 quantity
            $product->quantity = $product->father_quantity;
            $product->save();

*/








}
