<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\CheckoutOrderRequest;
use App\Http\Resources\Api\V1\Order\OrderIndexResource;
use App\Models\Ecommerce\Product\Order\Order;
use App\Repositories\Ecommerce\Order\OrderRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class OrderController extends Controller
{
    /**
     * (*) User's orders
     */
    public function index()
    {
        return response()->rest_paginate(
            OrderIndexResource::collection(
                auth()->user()->orders()->with(['items', 'items.product', 'paymentType'])->latest()->paginate(20)
            )
        );
    }

    /**
     * (*) Return available times to make an order
     */
    public function time(): JsonResponse
    {
        return response()->rest(OrderRepository::availableTimes());
    }

    /**
     * (*) Store order
     */
    public function store(CheckoutOrderRequest $request): JsonResponse
    {
        $order = (new OrderRepository($request->all()))->create();

        $url = null;
        if ($request->payment_type_id == 3) {
            $response = createHalkbankOrder('010');

            if ($response['status'] == 'success') {
                $url = $response['url'];

                $order->update([
                    'halkbank_id' => $response['orderId'],
                ]);
            }
        }

        return response()->rest([
            'order_id' => $order->id,
            'payment_url' => $url,
        ], 201);
    }

    /**
     * (*) Show order
     */
    public function show(Order $order): JsonResponse
    {
        $order->load(['items', 'items.product', 'paymentType']);

        return response()->rest(new OrderIndexResource($order));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, Order $order): JsonResponse
    {
        // $order-.

        return response()->rest();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        return response()->rest();
    }
}
