<?php

namespace App\Http\Controllers\AdminControllers;

use Illuminate\Http\Request;
use App\Models\Order;

class OrderController
{
    public function orderList(Request $request){
        return view('admin.order-list');
    }

    public function ordersByStatus(Request $request)
    {
        $status = $request->status;
        $orders = Order::where('order_status', $status)->paginate(5);
        $data = [];

        foreach ($orders as $index => $order) {
            $data[] = [
                'sr_no' => $index + 1,
                'order_id' => $order->order_id,
                'date' => $order->created_at->format('d M Y'),
                'total' => '₹' . $order->total,
                // 'status' => $order->order_status . ' <a href="javascript:void(0);" class="link-success fs-15 edit-status" data-id="' . $order->id . '" data-status="' . $order->order_status . '"><i class="ri-edit-2-line"></i></a>',
                'status' => $order->order_status,
                'expected_date' => $order->expected_date ? \Carbon\Carbon::parse($order->expected_date)->format('d M Y') : '',
                'action' => '<a href="' . route('orders.view', $order->id) . '"  class="link-success fs-15" ><i class="fas fa-eye"></i></a> <a href="javascript:void(0);" class="link-success fs-15 edit-status" data-id="' . $order->id . '" data-status="' . $order->order_status . '" data-expected-date="' . $order->expected_date . '">
                <i class="ri-edit-2-line"></i></a>',
                // 'action' => '<a href="">View</a>',
            ];
        }

         return response()->json([
        'orders' => $data,
        'pagination' => (string) $orders->links('pagination::bootstrap-4')
        ]);
    }

    public function ordersView($id)
    {
       $order = Order::where('id', $id)->with(['product'=> function($q){
                $q->select('id', 'name');
       }])->first();
       return view('admin.order-details', compact('order'));
    }

    public function updateStatus(Request $request)
    {
        $request->validate([
            'order_id' => 'required|exists:orders,id',
            'order_status' => 'required|string',
            'expected_date' => 'required'
        ]);

        $order = Order::findOrFail($request->order_id);
        $order->order_status = $request->order_status;
        $order->expected_date = $request->expected_date;
        $order->save();

        return response()->json(['success' => true]);
    }


}
