<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Order;
use App\Models\Cart;
use App\Models\Billing;
use Illuminate\Support\Str;

class OrderController
{
    public function saveOrder(Request $request){

        $validated = $request->validate([
          'first_name' => 'required|string|max:255',
          'phone' => 'required',
          'email' => 'required',
          'address' => 'required',
          'state' => 'required',
          'city' => 'required',
          'post_code' => 'required'
        ]);

        $billing = new Billing($request->all());
        $billingSave = $billing->save();

        $data = array(
            'user_id' => $request->user_id,
            'billing_id' => $billing->id,
            'total' => $request->total,
            'coupon_discount' => $request->coupon_discount,
            'payment_method' => $request->payment_method,
        );
        $ordersave = $this->saveOrderValue($data);

        if ($billingSave) {
            $aa = Cart::where('user_id', $request->user_id)->delete();
            return view('success', ['orderId' => $ordersave->order_id]);
            // return redirect()->back()->with('success', 'Your order is successfully placed!');
        }

        return redirect()->back()->with('error', 'Your order is not placed !');
    }

    public function saveOrderValue($data){

        $cart = Cart::where('user_id', $data['user_id'])->get();
        $orderId = 'ORD-' . strtoupper(Str::random(3)) . rand(1000, 9999);
        foreach($cart as $value){

           $order = new Order;
           $order->user_id = $data['user_id'];
           $order->billing_id = $data['billing_id'];
           $order->order_id = $orderId;
           $order->product_id = $value->product_id;
           $order->qty = $value->quantity;
           $order->mrp = $value->sub_total;
           $order->total = $data['total'];
           $order->coupon_code = $value->coupon_code;
           $order->coupon_discount = $data['coupon_discount'];
           $order->payment_method = $data['payment_method'];
           $order->payment_status = 'Pending';
           $order->order_status = 'pending';
           $order->save();

        } 
        return $order;     

    }
    
    public function myAccount(){

        $id = Auth::user()->id;
        $user = User::where('id', $id)->first();
        return view('my-account', compact('user'));
    }

    public function updateAccount(Request $request, $user_id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $user_id,
            'mobile' => 'required|max:10|unique:users,mobile,' . $user_id
        ]);

        $user = User::findOrFail($user_id);
        $user->name = $request->name;
        $user->email = $request->email;
        $user->mobile = $request->mobile;

        if ($user->save()) {
            return back()->with('success', 'Your account has been updated successfully!');
        } else {
            return back()->with('error', 'Your account was not updated!');
        }
    }
    
    public function myOrder(Request $request){

        $id = Auth::user()->id;
        $orders = Order::where('user_id', $id)
        ->with(['billing', 'product' => function ($q) {
            $q->select('id', 'name');
        }])
        ->orderBy('created_at', 'desc')
        ->paginate(5); // Show 5 orders at a time

        if ($request->ajax()) {
            return view('partials.orders_rows', compact('orders'))->render();
        }
        return view('order', compact('orders'));

    }
    
    public function orderDetails($id){
       $userId = Auth::guard('user')->user()->id;  
       $order = Order::where('id', $id)->where('user_id', $userId)->with('billing')->first();
       return view('order-details', compact('order'));
    }
}
