<?php

namespace App\Http\Controllers\Orders;


use App\Classes\Modules\Orders\Services\GeneratesUniqueOrderNumber;
use App\Classes\ValueObjects\Constants\HttpStatus;
use App\Classes\ValueObjects\Response\ApiResponseObject;
use App\Http\Resources\OrderResource;
use App\Models\Company;
use App\Models\Order;
use Illuminate\Http\Request;

class OrderController
{

    public function create(Request $request, GeneratesUniqueOrderNumber $generatesUniqueOrderNumber){

        try {

                /** @var Company $company */
            $company = Company::findOrFail($request->company_id);

            $order = new Order();
            $order->company_id = $company->id;
            $order->order_number = $generatesUniqueOrderNumber->execute();
            $order->forwarder_id = 1;
            $order->address_id = $company->addresses()->first()->id;
            $order->contact_id = $company->contacts()->first()->id;
            $order->current_step = 'MS_WAREHOUSE_RECEIVING';
            $order->multiple_batch = false;
            $order->complete = false;

            $order->save();

            $order->warehouses()->attach($request->warehouse_id === 1 ? 3 : 2);

            return (new ApiResponseObject('New Order',
                'Order has been placed successfully',
                HttpStatus::OK_WITH_MESSAGE, []))->handler();

        } catch (\Exception $exception){
            return (new ApiResponseObject('New Order',
                $exception->getMessage(),
                $exception->getCode(), []))->handler();

        }

    }


    public function list(String $companyId){

        $orders = Order::where('company_id', $companyId)->orderBy('created_at', 'DESC')
            ->paginate(10);
        return (new ApiResponseObject('',
            '',
            HttpStatus::OK_WITH_MESSAGE, json_decode(OrderResource::collection($orders)->response()->getContent(), true)))->handler();
    }

    public function download(String $orderId){
        /** @var Order $order */
        $order = order::findOrFail($orderId);
        /** @var Company $warehouse */
        $warehouse = $order->warehouses()->first();
        $warehouseAddress = $warehouse->addresses()->first();
        $warehouseContact = $warehouse->contacts()->get();

        $data = [
            'order' => $order,
            'company' => $order->importer(),
            'delivery_address' => $order->address,
            'warehouse_address' => $warehouseAddress,
            'warehouse_contact' => $warehouseContact
        ];

        return view('pages.pdf.qr', $data);

        return $this->pdf->loadView('pages.pdf.qr', $data)->stream();
    }

}