<?php

namespace App\Http\Controllers\Api;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\SalesOrderRequest;
use App\Http\Resources\SalesOrderResource;
use App\Models\SalesOrder;
use App\Services\SalesOrderService;
use Illuminate\Http\Request;

class SalesOrderController extends Controller
{
    protected $service;

    public function __construct(SalesOrderService $service)
    {
        $this->service = $service;
    }

    public function index(Request $request)
    {
        $orders = $this->service->list($request);
    
        return ApiResponse::pagination(
            $orders,
            SalesOrderResource::class,
            'Orders fetched successfully.'
        );
    }

    public function store(SalesOrderRequest $request)
    {
        $order = $this->service->store($request);

        return ApiResponse::success(
            'Order created successfully.',
            new SalesOrderResource($order)
        );
    }

    public function show(SalesOrder $salesOrder)
    {
        return ApiResponse::success(
            'Order fetched successfully.',
            new SalesOrderResource(
                $this->service->show($salesOrder)
            )
        );
    }

    public function update(
        SalesOrderRequest $request,
        SalesOrder $salesOrder
    ) {
        $order = $this->service->update(
            $request,
            $salesOrder
        );

        return ApiResponse::success(
            'Order updated successfully.',
            new SalesOrderResource($order)
        );
    }

    public function destroy(SalesOrder $salesOrder)
    {
        $this->service->delete($salesOrder);

       return ApiResponse::success(
            'Order deleted successfully.'
        );
    }

    public function confirm(SalesOrder $salesOrder)
    {
        $order = $this->service->confirm($salesOrder);

       return ApiResponse::success(
            'Order confirmed successfully.',
            new SalesOrderResource($order)
        );
    }

    public function cancel(SalesOrder $salesOrder)
    {
        $order = $this->service->cancel($salesOrder);

        return ApiResponse::success(
            'Order cancelled successfully.',
            new SalesOrderResource($order)
        );
    }
    
    public function myOrders(Request $request)
    {
        $orders = $this->service->myOrders($request);
    
        return ApiResponse::success(
            'Sales orders fetched successfully.',
            SalesOrderResource::collection($orders)
        );
    }
}