<?php

namespace Modules\Order\Controllers\Canteen;

/** Ajax Request */

use App\Exports\OrderExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Services\Response\ResponseService;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Modules\Canteen\Services\CanteenService;
use Modules\Order\Requests\Admin\OrderRequest;
use Modules\Order\Services\OrderService;

class OrderController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/canteen/orders';
    /** View folder */
    private $viewDirectory= 'canteen.orders.';
    //

    public function __construct(
        private OrderService $orderService,
        private CanteenService $canteenService,
    )
    {}

    /**
     * Display a listing of the orders.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('orders.head');
        $canteens = $this->canteenService->get();
        return view($this->viewDirectory.'index', get_defined_vars());
    }

    /**
     * return data of the orders.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request)
    {
        if (!isset($request->export))
        {
            $request->merge(['paginate'=>true,'canteen_id'=>auth()->user()->canteen_id]);
        }

        $orders= $this->orderService->get($request->all());

        if (isset($request->export))
        {
            return Excel::download(new OrderExport($orders, 'orders'), 'Orders.xlsx');
        }
        return view($this->viewDirectory.'grid',get_defined_vars());
    }


    /**
     * Show the form for editing the specified Order.
     *
     * @param  int $id
     * @return View
     */
    public function edit(int $id) :View
    {
        $order = $this->orderService->getItem($id);
        if (!$order && ($order->canteen_id == auth()->user()->canteen_id ?? false))
        {
            abort(404);
        }
        $head= __('orders.edit');
        $canteens = $this->canteenService->get();

        return view( $this->viewDirectory.'form', get_defined_vars() );
    }

}
