<?php

namespace App\Http\Controllers;

use App\Models\Address;
use Illuminate\Http\Request;
use App\Models\Cart;

use App\Models\Order;
use App\Models\Shipping;
use App\User;
use Illuminate\Support\Facades\Notification;
use Helper;
use Illuminate\Support\Str;
use App\Notifications\StatusNotification;


use Barryvdh\DomPDF\Facade as PDF;

class OrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $orders = Order::orderBy('id', 'DESC')->paginate(10);
        return view('backend.order.index')->with('orders', $orders);
    }

    /**
     * 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)
    {

        $isSubscription = Cart::where('user_id', auth()->user()->id)
            ->where('item_type', 'subscription')
            ->exists();

        $hasProduct = Cart::where('user_id', auth()->user()->id)
            ->where('item_type', 'product')
            ->exists();

        if ($isSubscription && $hasProduct) {
            return back()->with('error', 'You cannot checkout subscription and products together');
        }



        if (empty(Cart::where('user_id', auth()->user()->id)
            ->where('order_id', null)
            ->first())) {
            return back()->with('error', 'Cart is Empty!');
        }



        if ($isSubscription && $request->payment_method === 'cod') {
            return back()->with('error', 'Cash on Delivery is not allowed for subscriptions');
        }

        if ($isSubscription) {
            $this->validate($request, [
                'payment_method' => 'required'
            ]);
        } else {
            $this->validate($request, [
    'first_name' => 'string|required',
    'last_name'  => 'string|required',
    'address1'   => 'string|required',
    'address2'   => 'string|nullable',
    'city'       => 'required|string',
    'state'      => 'required|string',
    'country'    => 'nullable|string',
    'coupon'     => 'nullable|numeric',
    'phone'      => 'numeric|required',
    'post_code'  => 'string|nullable',
    'email'      => 'string|required',
    'shipping_cost' => 'required|numeric|min:0',
    'courier_name'  => 'nullable|string',
    'payment_method' => 'required'
]);

        }


        $order = new Order();
        $order_data = $request->all();
        $order_data['order_type'] = $isSubscription ? 'subscription' : 'product';

        $order_data['order_number'] = 'ORD-' . strtoupper(Str::random(10));
        $order_data['user_id'] = $request->user()->id;

        //$order_data['shipping_id']=$request->shipping;
        //$shipping=Shipping::where('id',$order_data['shipping_id'])->pluck('price');
        $shipping_price = $isSubscription ? 0 : ($request->shipping_cost ?? 0);

        if ($shipping_price < 0 || $shipping_price > 5000) {
            abort(400, 'Invalid shipping amount');
        }

        $order_data['delivery_charge'] = $shipping_price;
        $order_data['courier_name']    = $request->courier_name ?? null;
        $order_data['courier_id'] = $request->courier_id;

        // return session('coupon')['value'];
        //$order_data['sub_total'] = Helper::totalCartPrice();
        //$order_data['quantity'] = Helper::cartCount();
        if ($isSubscription) {
            $order_data['sub_total'] = Helper::subscriptionTotal();
            $order_data['quantity'] = 1;
        } else {
            $order_data['sub_total'] = Helper::totalCartPrice();
            $order_data['quantity'] = Helper::cartCount();
        }

        if (session('coupon')) {
            $order_data['coupon'] = session('coupon')['value'];
        }
        $subTotal = $order_data['sub_total'];
        $discount = session('coupon')['value'] ?? 0;

        if ($isSubscription) {
            $order_data['total_amount'] = $subTotal;
        } else {
            $order_data['total_amount'] = $subTotal + $shipping_price - $discount;
        }


        // return $order_data['total_amount'];
$order_data['status'] = "new";

$order_data['payment_method'] = $request->payment_method;

if ($request->payment_method == 'cod') {
    $order_data['payment_status'] = 'pending';
} else {
    $order_data['payment_status'] = 'paid';
}

$order_data['city']  = $request->city;
$order_data['state'] = $request->state;
$order_data['country'] = $request->country ?? 'India';

$order->fill($order_data);

        $status = $order->save();
        if ($order)
            // dd($order->id);
            $users = User::where('role', 'admin')->first();
        $details = [
            'title' => 'New order created',
            'actionURL' => route('order.show', $order->id),
            'fas' => 'fa-file-alt'
        ];
        Notification::send($users, new StatusNotification($details));
        if (request('payment_method') == 'paypal') {
            return redirect()->route('payment')->with(['id' => $order->id]);
        } else {
            //session()->forget('cart');
            session()->forget('coupon');
        }
        Cart::where('user_id', auth()->user()->id)->where('order_id', null)->update(['order_id' => $order->id]);

        //  Save address if user checked the box
        if ($request->save_address) {
            Address::updateOrCreate(
                [
                    'user_id'   => auth()->id(),
                    'address1'  => $request->address1,
                    'post_code' => $request->post_code,
                ],
                [
                    'label'      => 'Saved Address',
                    'first_name' => $request->first_name,
                    'last_name'  => $request->last_name,
                    'phone'      => $request->phone,
                    'email'      => $request->email,
                    'country'    => $request->country,
                    'city'       => $request->city,
                    'state'      => $request->state,
                    'address2'   => $request->address2,
                ]
            );
        }

        // dd($users);        
        //request()->session()->flash('success', 'Your product successfully placed in order');
        $message = $isSubscription
            ? 'Your subscription has been activated successfully'
            : 'Your product order has been placed successfully';

        request()->session()->flash('success', $message);

        return redirect()->route('payment.success.page');
    }



public function approveExchange($id)
{
    $order = Order::findOrFail($id);

    if ($order->exchange_status != 'requested') {
        return back()->with('error', 'Exchange not requested by customer');
    }

    if ($order->return_shipment_id) {
        return back()->with('error', 'Return pickup already scheduled');
    }

    $shiprocket = app(\App\Services\ShiprocketService::class);

    $response = $shiprocket->createReturnPickup($order);

    if (!$response || !isset($response['shipment_id'])) {
        return back()->with('error','Failed to schedule pickup');
    }

    $order->update([
        'exchange_status'     => 'pickup_scheduled',
        'return_shipment_id'  => $response['shipment_id'],
        'return_awb_code'     => $response['awb_code'] ?? null
    ]);

    return back()->with('success','Return pickup scheduled successfully');
}
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $order = Order::find($id);
        // return $order;
        return view('backend.order.show')->with('order', $order);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $order = Order::find($id);
        return view('backend.order.edit')->with('order', $order);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $order = Order::find($id);
        $this->validate($request, [
            'status' => 'required|in:new,process,delivered,cancel'
        ]);
        $data = $request->all();
        // return $request->status;
        if ($request->status == 'delivered') {
            foreach ($order->cart as $cart) {
                $product = $cart->product;
                // return $product;
                $product->stock -= $cart->quantity;
                $product->save();
            }
        }
        $status = $order->fill($data)->save();
        if ($status) {
            request()->session()->flash('success', 'Successfully updated order');
        } else {
            request()->session()->flash('error', 'Error while updating order');
        }
        return redirect()->route('order.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $order = Order::find($id);
        if ($order) {
            $status = $order->delete();
            if ($status) {
                request()->session()->flash('success', 'Order Successfully deleted');
            } else {
                request()->session()->flash('error', 'Order can not deleted');
            }
            return redirect()->route('order.index');
        } else {
            request()->session()->flash('error', 'Order can not found');
            return redirect()->back();
        }
    }


    public function paymentSuccess($order_id)
{
    $order = Order::with('cart_info.product')->findOrFail($order_id);

    return view('frontend.pages.payment-success', compact('order'));
}


    public function orderTrack()
    {
        return view('frontend.pages.order-track');
    }

    public function productTrackOrder(Request $request)
    {
        // return $request->all();
        $order = Order::where('user_id', auth()->user()->id)->where('order_number', $request->order_number)->first();
        if ($order) {
            if ($order->status == "new") {
                request()->session()->flash('success', 'Your order has been placed. please wait.');
                return redirect()->route('home');
            } elseif ($order->status == "process") {
                request()->session()->flash('success', 'Your order is under processing please wait.');
                return redirect()->route('home');
            } elseif ($order->status == "delivered") {
                request()->session()->flash('success', 'Your order is successfully delivered.');
                return redirect()->route('home');
            } else {
                request()->session()->flash('error', 'Your order canceled. please try again');
                return redirect()->route('home');
            }
        } else {
            request()->session()->flash('error', 'Invalid order numer please try again');
            return back();
        }
    }

    // PDF generate
    public function pdf(Request $request)
{
    $order = Order::with(['cart_info.product'])->findOrFail($request->id);

    $file_name = $order->order_number.'.pdf';

    $pdf = PDF::loadView('invoices.order', compact('order'));

    return $pdf->download($file_name);
}
    // Income chart
    public function incomeChart(Request $request)
    {
        $year = \Carbon\Carbon::now()->year;
        // dd($year);
        $items = Order::with(['cart_info'])->whereYear('created_at', $year)->where('status', 'delivered')->get()
            ->groupBy(function ($d) {
                return \Carbon\Carbon::parse($d->created_at)->format('m');
            });
        // dd($items);
        $result = [];
        foreach ($items as $month => $item_collections) {
            foreach ($item_collections as $item) {
                $amount = $item->cart_info->sum('amount');
                // dd($amount);
                $m = intval($month);
                // return $m;
                isset($result[$m]) ? $result[$m] += $amount : $result[$m] = $amount;
            }
        }
        $data = [];
        for ($i = 1; $i <= 12; $i++) {
            $monthName = date('F', mktime(0, 0, 0, $i, 1));
            $data[$monthName] = (!empty($result[$i])) ? number_format((float)($result[$i]), 2, '.', '') : 0.0;
        }
        return $data;
    }
}
